package com.example.demo.controller;

import com.example.demo.common.TokenCommon;
import com.example.demo.pojo.User;
import com.example.demo.service.RedisService;
import com.example.demo.service.TokenService;
import com.example.demo.service.UserService;
import com.example.demo.util.MD5Util;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController("password")
@RequestMapping("amend")
public class AmendController {

    @Resource
    private RedisService redisService;
    @Resource
    private UserService userService;
    @Resource
    private TokenService tokenService;
    private final TokenCommon tokenCommon = new TokenCommon();

    @PostMapping("password")
    public TokenCommon password(@RequestParam("password") String password,
                                @RequestParam("newPassword") String newPassword,
                                @RequestHeader("Authorization") String token) {
        Map<String, String> TokenMap = this.tokenService.parseToken(token);
        String email = TokenMap.get("email");
        List<User> userServiceDiaryUser = this.userService.getUser(email);
        String userPassword = userServiceDiaryUser.get(0).getPassword();
        if (Objects.equals(userPassword, MD5Util.md5(password))) {
            String newHxPassword = this.userService.updateUserPassword(email, newPassword);
            String newToken = this.tokenService.getToken(email, newHxPassword);
            return this.tokenCommon.tokenJSON(email, true, 200, newToken);
        }
        return this.tokenCommon.tokenJSON(email, false, 500, "密码错误！");

    }

    @PostMapping("auth")
    private TokenCommon auth(@RequestParam("email") String email,
                             @RequestParam("auth") String auth,
                             @RequestParam("password") String password) {
        List<User> userServiceDiaryUser = this.userService.getUser(email);
        if (!userServiceDiaryUser.isEmpty()) {
            String Auth = this.redisService.get("AUTH2" + email);
            if (Objects.equals(Auth, auth)) {
                String newHxPassword = this.userService.updateUserPassword(email, password);
                String token = this.tokenService.getToken(email, newHxPassword);
                this.redisService.delete("AUTH2" + email);
                return this.tokenCommon.tokenJSON(email, true, 200, token);
            }
            return this.tokenCommon.tokenJSON(email, false, 500, "验证码错误！");
        }
        return this.tokenCommon.tokenJSON(email, false, 500, "账号不存在！不能修改密码");
    }
}
